package com.pub.paypal.service.impl;

import com.pub.paypal.common.util.HttpUtils;
import com.pub.paypal.config.PaypalConfig;
import com.pub.paypal.model.PayPalCheckoutConstant;
import com.pub.paypal.service.CallbackService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Map;

@Service
@Slf4j
@AllArgsConstructor
public class CallbackServiceImpl implements CallbackService {
    /**
     * 回调
     * @param map
     */
    @Override
    public String callback(@SuppressWarnings("rawtypes") Map map) {

        log.info(map.toString());
        String outTradeNo = (String)map.get("invoice");
        String paymentStatus = (String)map.get("payment_status");
        String amount = (String)map.get("mc_gross");
        String currency = (String)map.get("mc_currency");
        String paymentId = (String)map.get("txn_id");
        String parentPaymentId = (String)map.get("parent_txn_id");
        log.info("商家订单号 = {}", outTradeNo);
        log.info("订单状态 = {}", paymentStatus);
        log.info("金额 = {}", amount);
        log.info("币种 = {}", currency);
        log.info("流水号 = {}", paymentId);
        log.info("父流水号 = {}", parentPaymentId);
        FormBody.Builder body = new FormBody.Builder();
        body.add("cmd","_notify-validate");  //不携带的话请求是无效的
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){  //所有paramMap的参数必须全部返回才可以检验
            Map.Entry<String, String> next = iterator.next();
            body.add(next.getKey(),next.getValue());
        }
        String result = HttpUtils.netForm("https://ipnpb.sandbox.paypal.com/cgi-bin/webscr", body.build());
        //VERIFIED-验签成功 INVALID-验签失败
        if (!"VERIFIED".equals(result)){
            log.error("ipn参数被篡改，请求无效");
            return "failure";
        }
        if (!PaypalConfig.EMAIL.equals(map.get("receiver_email"))) {
            log.info("FAIL = 商户id错误, outTradeNo = {}", outTradeNo);
            return "failure";
        }
        if("Completed".equals(paymentStatus)) {
            //修改本地状态
            log.info("支付成功,状态为=COMPLETED");
            return PayPalCheckoutConstant.SUCCESS;
        }
        //退款操作
        if("Refunded".equals(paymentStatus)) {
            //进行本地数据库操作之后返回退款成功标识
            log.info("退款成功");
            return PayPalCheckoutConstant.SUCCESS;
        }
        if("Pending".equals(paymentStatus) && StringUtils.isEmpty(parentPaymentId)) {
            String pendingReason = String.valueOf(map.get("pending_reason"));
            //进行数据库操作
            log.info("订单支付成功,状态为=PENDING，产生此状态的原因是 {}", pendingReason );
            return PayPalCheckoutConstant.SUCCESS;
        }
        if(StringUtils.isEmpty(parentPaymentId)) {
            if(PayPalCheckoutConstant.PAYMENT_STATUS_REVERSED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_CANCELED_REVERSAL.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_DENIED.equals(paymentStatus)) {
                String reasonCode = String.valueOf(map.get("reason_code"));
                //进行数据库操作(状态修改)
                log.info("订单异常,请尽快查看处理，状态为={}，产生此状态的原因是 {} ", paymentStatus, reasonCode);
                return PayPalCheckoutConstant.SUCCESS;
            }
            if(PayPalCheckoutConstant.PAYMENT_STATUS_EXPIRED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_CREATED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_FAILED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_PROCESSED.equals(paymentStatus)
                    || PayPalCheckoutConstant.PAYMENT_STATUS_VOIDED.equals(paymentStatus)) {
                //进行数据库操作(状态修改)
                log.info("其他订单状态,订单异常,请尽快查看处理， 状态={}", paymentStatus);
                return PayPalCheckoutConstant.SUCCESS;
            }
        }
        return "failure";
    }
}
